package com.sq.partner.manager.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.sq.partner.manager.sso.filter.SSOFilter;
import com.sq.partner.manager.util.LogUtil;

/**
 * 特殊字符过滤
 * 过滤掉 以 <中间有字母>这种形式
 */
public class ManagerXssFilter implements Filter {
	private static Logger logger = LogUtil.getLog(ManagerXssFilter.class);
	private static Pattern pattern = Pattern.compile("<\\s*.*[a-zA-Z]+.*\\s*>*");

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * 权限验证
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		Enumeration<String> names = req.getParameterNames();
		boolean checkOk = true;
		String msg = null;
		if(names != null){
			while(names.hasMoreElements()){
				String name = names.nextElement();
				String[] vals = request.getParameterValues(name);
				for(String val : vals){
					Matcher m = pattern.matcher(val);
					if(m.find()){
						val = val.replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
						msg = "参数["+name+"]值["+val+"]非法";
						checkOk = false;
			            break;
					}
				}
				if(!checkOk){
					break;
				}
			}
		}
		
		if(checkOk){
			chain.doFilter(request, response);
		}else{
			req.setAttribute("dispatchUri", "/common/error");
            SSOFilter.doLoginError(req, res, msg);
		}
			
	}
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}
}
